import axios from 'axios'
import { Toast } from 'vant'

import { getLocal } from '@/utils/local'
// axios.defaults.baseURL = 'http://localhost:1337'
axios.defaults.baseURL = process.env.VUE_APP_URL
axios.interceptors.request.use(
  function (config) {
    const needToken = config.needToken

    const token = getLocal('token')

    if (needToken) {
      if (token) {
        config.headers.authorization = `Bearer ${token}`
      }
    }

    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  function (response) {
    const code = response.data.code
    if (code === 200) {
      return response.data
    } else if (code === 400 || code === 401 || code === 403) {
      Toast.fail(response.data.message)
      return Promise.reject(new Error(response.data.message))
    }
  },
  function (error) {
    return Promise.reject(error)
  }
)

export default axios
